<template>
    <eui-page-frame topHeight="170" :bottomHeight="bottomHeight">
        <template #top>
            <view class="navigation">
                <eui-nav-bar :title="title" color="#000000" rightIcon="" />
            </view>
        </template>
        <eui-page-content>
            <eui-base-card :title="subTitle">
                <template #right>
                    <eui-tag :text="detailData.work_status_name" :type="'待评价,已完成'.includes(detailData.work_status_name)?'success':(detailData.work_status_name=='已驳回'?'warning':undefined)" plain plainFill :showBorder="false"> </eui-tag>
                </template>
                <eui-detail-show :items="dataItems" v-model="detailData" labelWidth="80px"></eui-detail-show>
                <UploadFile :autoUpload="false" :disabled="true" :readonly=true fileMediatype="image"
                    :fileId="detailData.bill_id" fileClass="物业服务申请单" return-type="array" mode="grid"></UploadFile>
            </eui-base-card>

            <eui-card title="收费项目" hMargin="0" v-if="detailData.con_no && props.billType === '维修派工' && feeDatas.length > 0" showTitleLine="true" hPadding="32"
                style="width: 100%; margin: 16rpx 0;">
                <view v-for="(itemData, index) in feeDatas" :key="index">
                    <eui-card-input v-for="(item, index) in feeDataItems" :key="index" 
                        v-model="itemData[item.modelvalue]" :title="item.title" :placeholder="item.placeholder"
                        :type="item.type" :maxlength="item.maxlength"
                        :displayable="((!readonly) ? item.displayable : readonly)"
                        :rightIconType='((!readonly) && item.selectType) ? "right" : ""'
                        @iconClick='item.selectType ? selectOpen(item.selectType, itemData) : () => { }' />
                    <view v-show="(!readonly)" class="add-del-view">
                        <eui-button type="min" title="添加费用" @click="addClick"></eui-button>
                        <eui-button type="min2" title="删除费用" @click="delClick(itemData.c_sort)"></eui-button>
                    </view>
                </view>
            </eui-card>

            <eui-card title="处理信息" hMargin="0" v-if="needHandleStatus.includes(detailData.work_status)" showTitleLine="true" hPadding="32">
                <eui-card-input v-model="detailData.handleUser" title="处理人" placeholder="请选择人员" type="text" 
                    displayable="false" rightIconType="right" @iconClick="selectOpen('user')" />

                <eui-card-input v-model="detailData.handleContent" title="处理说明" placeholder="请输入处理说明" type="textarea" 
                    maxlength="200" />
            </eui-card>
            <eui-base-card v-if="handledStatus.includes(detailData.work_status)" title="审批意见" style="width: 100%; margin: 16rpx 0;">
                <eui-detail-show :items="handleDataItems" v-model="detailData" labelWidth="80px"></eui-detail-show>
            </eui-base-card>
        </eui-page-content>
        <template #bottom>
            <view v-if="isShowVerifyButton || needHandleStatus.includes(detailData.work_status)" class="bottom">
                <eui-button v-if="isShowVerifyButton" type="primary" style="display: block;" title="确认核销" @click="verify" />
                <view v-if="needHandleStatus.includes(detailData.work_status)" style="display: flex; justify-content: space-between;">
                    <eui-button v-if="(detailData.work_status === '0' && props.billType !== '维修派工')" type="base2"
                        title="驳回" @click="reject" />
                    <eui-button v-else-if="(detailData.work_status === '1' && props.billType === '维修派工')" type="base2"
                        title="保存" @click="save" />
                    <eui-button v-if="needHandleStatus.includes(detailData.work_status)" type="base" title="提交处理" @click="submit" />
                </view>
            </view>
        </template>
    </eui-page-frame>
</template>

<script setup lang="ts">
import store from '@/store';
import { computed, onMounted, ref, watch } from 'vue'
import useService from '@/hooks/useService';
import dateRangUtil from '../../../common/dateRangUtil';
import UploadFile from '@/components/UploadFile.vue';
import type { PropertyTaskFee } from '../types/propertyTypes/property';
import { getRelatedName } from '../components/RelatedName.js';

const { loginInfo } = store.state.value.main;

const service = useService({ prefix: "apiApi" });

const currentItem = ref({});

const bottomHeight = ref(0);

const props = defineProps<{
    id?: string;  // 工单编号
    project?: string; // 工单项目
    billType?: string; // 单据类型
}>();

const id = ref('');
const title = ref('');
const subTitle = ref('申请信息');

const maxSort = ref(1);

const uniqueKey = '管易通物业模块服务';

const needHandleStatus = ref('0,1,4') //未处理状态; 0: 待确认, 1: 待处理, 2: 已作废; 3: 待评价, 4: 已完成,9: 已驳回;
const handledStatus = ref('2,3,4,9') //已处理状态

const showFee = ref(false)
const readonly = ref(false)

const detailData = ref({
    tenant_id: '',
    id: '',
    bill_id: '',
    bill_type: '',
    project: '',
    user: '',
    userno: '',
    date: undefined,
    content: '',
    remark: '',
    bill_status: '',
    work_status: '',
    work_status_name: '',
    partner: '',
    con_no: '',
    qrcode_count:0,
    qrcode_times:0,
    qrcode_dt:undefined,

    handleUser: '',
    handleUserno: '',
    handleDateTime: undefined,
    handleContent: '',
    // handleResult: '',
})

const isShowVerifyButton = computed(() => {
    var isShow = (props.project === '申请核验' && 
    detailData.value.work_status === '3' && 
    detailData.value.qrcode_count< detailData.value.qrcode_times && 
    detailData.value.qrcode_dt && 
    new Date(detailData.value.qrcode_dt) > new Date())
    return isShow
})  

watch(() => detailData.value.work_status, () => {
    readonly.value = handledStatus.value.includes(detailData.value.work_status)
})

const feeDataItems = [
    {
        title: "费用项目",
        modelvalue: "c_fee_show",
        type: "text",
        maxlength: 6,
        selectType: "feeItem",
        placeholder: "请选择费用项目",
        displayable: true
    },
    {
        title: "费用金额",
        modelvalue: "c_amount",
        type: "number2",
        maxlength: 10,
        selectType: "",
        placeholder: "请输入费用金额",
        displayable: false
    }
];

const feeDatas = ref<PropertyTaskFee[]>([
    {
        c_tenant_id: '',
        c_id: '',
        c_sort: maxSort.value++,
        c_fee_code: '',
        c_at_fee: 0.00,
        c_num: 1,
        c_amount: 0.00,
    }
])

const dataItems = ref([
    {
        label: "申请事项",
        prop: "project",
        type: "text",
        element: {
        },
    },
    {
        label: "商户",
        prop: "partner",
        type: "text",
        element: {
        },
    },
    {
        label: "合同号",
        prop: "con_no",
        type: "text",
        element: {
        },
    },
    
    {
        label: "申请人",
        prop: "user",
        type: "text",
        element: {
        },
    },
    {
        label: "申请时间",
        prop: "date",
        type: "text",
        element: {
            mode: 'YYYY-MM-DD HH:mm:ss'
        },
    },
    {
        label: "其他说明",
        prop: "content",
        type: "text",
        element: {
        },
    },
])

const handleDataItems = [
    {
        label: "审批人",
        prop: "handleUser",
        type: "text",
        element: {
        },
    },
    {
        label: "审批时间",
        prop: "handleDateTime",
        type: "text",
        element: {
            mode: 'YYYY-MM-DD HH:mm:ss'
        },
    },
    {
        label: "审批说明",
        prop: "handleContent",
        type: "text",
        element: {
        },
    },
]

const getData = async () => {
    console.log('getData', props)
    uni.showLoading({ title: "查询中...", mask: true });
    const res = await service.request('管易通物业模块服务', props.project=='申请核验'?'GetWorkDetailByBillId':'GetWorkDetail', props.id);
    uni.hideLoading();
    if (res) {
        const resObject = res;
        if (resObject) {
            const workData = resObject.ds[0];
            const workflowing = resObject.ds2?.filter(d => d.c_oper_method == '0')[0];
            const billMain = resObject.ds4[0];
            const billDetail = resObject.ds5;
            const feeDataDs = resObject.ds6;

            showFee.value = workData.c_is_fee == '1';

            detailData.value = {
                tenant_id: workData?.c_tenant_id,
                id: workData?.c_id,
                bill_id: workData?.c_bill_id,
                bill_type: workData?.c_bill_type,
                project: workData?.c_property_type_name,
                user: billMain?.c_req_user ?? '',
                userno: workflowing?.c_oper_userno,
                date: billMain?.c_req_dt,
                content: billMain?.c_question,
                remark: billMain?.c_note,
                bill_status: billMain?.c_status,
                work_status: workData?.c_status,
                work_status_name: workData?.c_work_status_name,
                con_no: billMain?.c_con_no||'',
                partner: billMain?.c_provider ? '[' + billMain.c_provider + ']' + getRelatedName('rdsProviders',billMain.c_provider) : '',
                qrcode_count: billMain?.c_qrcode_count||0,
                qrcode_times: billMain?.c_qrcode_times||0,
                qrcode_dt: billMain?.c_qrcode_dt||undefined,

                handleUser: workData?.c_process_userno ? '[' + workData?.c_process_userno + ']' + workData?.c_process_username : '[' + loginInfo.sUser + ']' + loginInfo.sUserName,
                handleUserno: workData?.c_process_userno || loginInfo.sUser,
                handleDateTime: workData?.c_process_edt || dateRangUtil.getCurrentDateTime(),
                handleContent: workData?.c_status == '9' ? (workData?.c_note || "") : (workData?.c_result || ""),
                // handleResult: workData?.c_status == '9' ? workData?.c_note : workData?.c_result,
            }
            bottomHeight.value = (needHandleStatus.value.includes(detailData.value.work_status) || isShowVerifyButton) ? 124 : 0;

            billDetail && billDetail.map(
                item => {
                    if (dataItems.value.every((x) => x.label != item.c_title)) {
                        dataItems.value.push({
                            label: item.c_title,
                            prop: 'value' + item.c_sort,
                            type: "text",
                            element: {
                            },
                        })
                    }
                    detailData.value['value' + item.c_sort] = item.c_options ? JSON.parse(item.c_options).filter(x => item.c_value.includes(x.value)).map(x => x.title).join(',') : item.c_value
                })
            if (feeDataDs.length > 0) {
                const mSort = Math.max.apply(Math, feeDataDs.map(item => { return item.c_sort })) + 1
                maxSort.value = mSort > maxSort.value ? mSort : maxSort.value;

                feeDatas.value = feeDataDs.map(x => {
                    return {
                        c_tenant_id: x.c_tenant_id,
                        c_id: x.c_id,
                        c_sort: x.c_sort,
                        c_fee_code: x.c_fee_code,
                        c_at_fee: x.c_at_fee,
                        c_num: x.c_num,
                        c_amount: x.c_amount,
                        c_fee_name: x.c_fee_name,
                        c_fee_show: '[' + x.c_fee_code + ']' + x.c_fee_name,
                    }
                })
            }
            else if (!(detailData.value.work_status == '1')) {
                feeDatas.value = []
            }
        }
        console.log("detailData111111: " + JSON.stringify(detailData.value));
        if(props.project=='申请核验')
        {
            if(detailData.value.qrcode_dt && new Date(detailData.value.qrcode_dt) < new Date()){
                // uni.showToast({
                //         duration: 2000,
                //         title: '该业务申请已经过期',
                //         icon: 'none'
                // });
                uni.showModal({
							title: '提示',
							content: '该业务申请已经过期',
							showCancel: false,
						});
            }
            if(detailData.value.qrcode_times<=detailData.value.qrcode_count) {
                // uni.showToast({
                //         duration: 2000,
                //         title: '该业务申请使用次数已全部使用',
                //         icon: 'none'
                //     });
                uni.showModal({
							title: '提示',
							content: '该业务申请使用次数已全部使用',
							showCancel: false,
						});
            }
        }
        
    }
}

onMounted(async () => {
    id.value = props.id ?? "";
    title.value = props.project + "详情";
    subTitle.value = props.project === "报事申请" ? "报事详情" : "申请信息";
    await getData();
})

/**增加费用项目*/
const addClick = () => {
    feeDatas.value.push({
        c_tenant_id: "",
        c_sort: maxSort.value++,
        c_fee_code: '',
        c_at_fee: 0.00,
        c_num: 1,
        c_amount: 0.00,
    })
}
/**删除费用项目*/
const delClick = (sort: number | string) => {
    if (feeDatas.value.length > 1) {
        feeDatas.value = feeDatas.value.filter(x => x.c_sort !== sort);
    }
    else if(feeDatas.value.length==1){
        feeDatas.value[0].c_amount = 0.00;
        feeDatas.value[0].c_fee_code = '';
        feeDatas.value[0].c_fee_show = '';
        feeDatas.value[0].c_fee_name = '';
    }
}
/**保存 */
const save = async () => {
    const feeToSave = feeDatas.value.map(x => {
        return {
            c_tenant_id: detailData.value.tenant_id,
            c_id: detailData.value.bill_id,
            c_sort: x.c_sort,
            c_fee_code: x.c_fee_code,
            c_at_fee: x.c_amount,
            c_num: 1,
            c_amount: x.c_amount,
        }
    })

    const saveModel = {
        workData: {
            c_tenant_id: detailData.value.tenant_id,
            c_id: detailData.value.id,
            c_process_userno: detailData.value.handleUserno,
            c_modify_userno: loginInfo.sUser,
            c_modify_dt: dateRangUtil.getCurrentDateTime(),
        },
        propertyTaskBill: {
            c_tenant_id: detailData.value.tenant_id,
            c_id: detailData.value.bill_id,
            c_bill_type: detailData.value.bill_type,
            c_result: detailData.value.handleContent
        },
        workFees: feeToSave
    }
    uni.showLoading({ title: "处理中...", mask: true });
    const result = await service.request(uniqueKey, 'SaveWorkData', saveModel);
    uni.hideLoading();
    if (result) {
        uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '保存成功!',
        });
        getData();
    }
}
/**驳回 */
const reject = async () => {
    uni.showModal({
        title: '提示',
        content: '确定要驳回该申请吗?',
        success: function (res) {
            if (res.confirm) {
                rejectWork();
            } else if (res.cancel) {
            }
        }
    });
}
const rejectWork = async () => {
    const req = {
        Id: detailData.value.id,
        BillId: detailData.value.bill_id,
        BillType: detailData.value.bill_type,
        Content: detailData.value.handleContent,
        UserNo: detailData.value.handleUserno
    }
    uni.showLoading({ title: "处理中...", mask: true });
    const res = await service.request(uniqueKey, 'RejectPropertyWork', req);
    console.log('cancelRes', res)
    uni.hideLoading();
    if (res) {
        uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '处理成功!',
        });
        getData();
    }
}
/**提交 */
const submit = async () => {
    if(props.billType === '维修派工' && feeDatas.value.length > 0){
        await save();
    }
    
    const req = {
        Id: detailData.value.id,
        BillId: detailData.value.bill_id,
        BillType: detailData.value.bill_type,
        Content: detailData.value.handleContent,
        UserNo: detailData.value.handleUserno
    }
    uni.showLoading({ title: "处理中...", mask: true });
    const res = await service.request(uniqueKey, 'CompletePropertyWork', req);
    console.log('submitRes', res)
    uni.hideLoading();
    if (res) {
        uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '处理成功!',
        });
        getData();
    }
}

const verifyWork=async () => {
    const req = {
        workData: {
            c_tenant_id: detailData.value.tenant_id,
            c_id: detailData.value.id,
            c_process_userno: detailData.value.handleUserno,
            c_modify_userno: loginInfo.sUser,
            c_modify_dt: dateRangUtil.getCurrentDateTime(),
        },
        propertyTaskBill: {
            c_tenant_id: detailData.value.tenant_id,
            c_id: detailData.value.bill_id,
            c_bill_type: detailData.value.bill_type,
            c_qrcode_count : (detailData.value.qrcode_count??0)+1,
        }
    }
    uni.showLoading({ title: "处理中...", mask: true });
    const res = await service.request(uniqueKey, 'UpdateQrcodeCount', req);
    uni.hideLoading();
    console.log('verifyRes', res)
    if (res) {

        uni.showModal({
            title: '提示',
            content: '核销成功',
            showCancel:false,
            success: function (res) {
                uni.navigateBack();
            }
        });
    }
};

/**核验 */
const verify = () => {
    uni.showModal({
        title: '提示',
        content: '确定要核验该申请吗?',
        success: function (res) {
            if (res.confirm) {
                verifyWork();
            } else if (res.cancel) {
            }
        }
    });
}

/**选择人员 */
const selectOpen = (selectType: string, item?: any) => {
    if (item) {
        currentItem.value = item;
    }
    uni.navigateTo({
        url: `../modals/index?type=${selectType}`
    });
}

const SelectionChanged = (type, item) => {
    console.log('SelectionChanged', type, item)
    switch (type) {
        case 'user':
            detailData.value.handleUser = '[' + item.value + ']' + item.text;
            detailData.value.handleUserno = item.value;
            break;
        case 'feeItem':
            console.log('currentItem', currentItem.value)
            if (currentItem.value) {
                currentItem.value.c_fee_code = item.value;
                currentItem.value.c_fee_name = item.text;
                currentItem.value.c_fee_show = '[' + item.value + ']' + item.text;
            }
            break;
    }
}

defineExpose({
    SelectionChanged
})
</script>

<style lang="scss">
@import '../../../uni.scss';

.content {
    display: flex;
    flex: 1;
    flex-direction: column;
    background-color: #F2F2F2;
    padding: 0rpx !important
}

.navigation {
    background: #FFFFFF;
    flex: 0 0 auto;
    margin-bottom: 0rpx;
}

.bottom {
    background-color: white;
    padding: 20rpx;
    height: 80rpx;
    width: 96%;
    bottom: 20rpx;
    right: 0rpx;
    position: fixed;
    margin-bottom: -20rpx;
}

.bt-button {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.view-text {
    font-size: $uni-font-size-base ;
}

.add-del-view {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
}
</style>